<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;

class Findpwd extends Controller
{
    public function _initialize()
    {
        if(Session::has('Username')&&Session::has('UserId'))
        {
            $this->success('您已登录!','../');
        }
    }
    
    public function index()
    {
    	return $this->fetch('findpwd');
    }

    public function changepwd()
    {
    	$param = request()->param();
    	$data = Db::name('user')->where('email',$param['email'])->where('changecode',$param['emailcode'])->select();
    	if(!$data){
    		return json(['message'=>'验证码错误!']);
    	}
		$param['password'] = pwd_md5($param['password']);
		$result = Db::name('user')->where('id',$data[0]['id'])->update(['password'=>$param['password'],'changecode'=>'']);
		if($result){
    		return json(['message'=>'密码更新成功!']);
		}else{
    		return json(['message'=>'密码更新失败!']);
		}
    }

    public function sendcode()
    {
    	$randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
		$code = substr($randStr,0,6);
		$email = request()->post('email');
		Db::name('user')->where('email',$email)->update(['changecode'=>$code]);
		$param['email'] = $email;
		$param['code'] = $code;
		$data = $this->sendemail($param);
		if($data){
			return json(['message'=>'邮件发送成功!']);
		}else{
			return json(['message'=>$data]);
		}
    }

    protected function sendemail($param)
    {
    	$toemail=$param['email'];
        $name='伯乐王';
        $subject='密码重置邮件';
        $content='这是您的重置密码邮件请谨慎保管验证码,您的验证码是:  '.$param['code'];
        send_mail($toemail,$name,$subject,$content);
    }
}
